# Name: CreateFishnets.py - MCBS 10/07/2014
# Description: Creates grids according to criterium

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Administrative feature that will determine the extent of the grid:
AdminFeature = "MicroRegions"
# Buffer feature that will determine the extent of the grid:
BufferFeature = "CSBuffer40km"

GridPrecision = '1000' # Meters

# GridName
GridName = "G1kmMiR" # Grid 1 km Micro Regions

arcpy.SpatialJoin_analysis(AdminFeature, BufferFeature, "AreaGrid", "", "KEEP_COMMON")
arcpy.Dissolve_management("AreaGrid", "AreaGridDissolved")
arcpy.Delete_management("AreaGrid")

# Get coordinates from ExtentFeatures to create the extent of fishnet:
desc = arcpy.Describe("AreaGridDissolved")

# # Set coordinate system of the output fishnet to the same as the Canasat maps:
# projec = "C:\Users\Marcelo\Documents\Sugarcane\Data\WorkedCanasat\CANASATprojection.prj"
# env.outputCoordinateSystem = arcpy.SpatialReference(projec)

OutputFirstGrid = GridName + "Big"

# Set the origin of the fishnet
originCoordinate = "%f %f" % (desc.extent.XMin,desc.extent.YMin)
# Set the orientation
yAxisCoordinate = "%f %f" % (desc.extent.XMin,desc.extent.YMin+1)

# Cell size in the same units as the coordinates
cellSizeWidth = GridPrecision
cellSizeHeight = GridPrecision

# Set to zero (number of rows and columns defined by cell size above)
numRows =  '0'
numColumns = '0'

# Opposite corner:
oppositeCorner = "%f %f" % (desc.extent.XMax,desc.extent.YMax)

# Create a point label feature class 
labels = 'LABELS'

# Each output cell will be a polygon
geometryType = 'POLYGON'

arcpy.CreateFishnet_management(OutputFirstGrid, originCoordinate, yAxisCoordinate, 
                              cellSizeWidth, cellSizeHeight, numRows, numColumns, 
							  oppositeCorner, labels, '#', geometryType)
# Label features:
LabelFeatures = OutputFirstGrid	+ "_label"					  
arcpy.SpatialJoin_analysis(LabelFeatures, "AreaGridDissolved", GridName, "", "KEEP_COMMON")
arcpy.SpatialJoin_analysis(OutputFirstGrid, "AreaGridDissolved", GridName + "Cell", "", "KEEP_COMMON")
arcpy.Delete_management(LabelFeatures)
arcpy.Delete_management(OutputFirstGrid)




